package com.lemt.sunmao.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lemt.sunmao.constant.EsConstant;
import com.lemt.sunmao.domain.User;
import com.lemt.sunmao.mapper.UserMapper;
import com.lemt.sunmao.response.ResponseCode;
import com.lemt.sunmao.response.ResponstData;
import com.lemt.sunmao.service.UserService;
import com.mysql.cj.util.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author lenovo
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 分页条件查询用户
     * */
    public ResponstData findPageUsers(String username, Integer currentPage, Integer pageSize) {
        try {
            System.out.println("条件"+username+"==="+pageSize);
            if(StringUtils.isNullOrEmpty(username)){
                System.out.println("没有条件时查询所有");
                int begin = (currentPage-1) * pageSize;
                List<User> users = userMapper.findPagecUsers(username,begin,pageSize);
                long count = userMapper.count(null);
                return new ResponstData(ResponseCode.SUCCESS,users,count);
            }
            System.out.println("es实现搜索");
            if(currentPage <= 1){
                currentPage = 1;
            }
            // 条件搜索
            SearchRequest searchRequest = new SearchRequest(EsConstant.USER_INDEX);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            // 分页
            searchSourceBuilder.from(currentPage-1);
            searchSourceBuilder.size(pageSize);
            // 分词器
            MatchPhraseQueryBuilder matchQuery = QueryBuilders.matchPhraseQuery("username",username);
            searchSourceBuilder.query(matchQuery);
            SearchSourceBuilder timeout = searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
            // 匹配项自定义高亮显示
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("username");
            highlightBuilder.requireFieldMatch(false); //是否多个高亮，即可能出现多次匹配(例vue基础是vue入门)
            highlightBuilder.preTags("<p class='infomessage' style='color:red'>");
            highlightBuilder.postTags("</p>");
            searchSourceBuilder.highlighter(highlightBuilder);

            // 执行搜索
            searchRequest.source(searchSourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println("结果"+searchResponse);
            //解析结果
            List<Map<String,Object>> list = new ArrayList();
            for (SearchHit hit : searchResponse.getHits().getHits()) {
//                list.add(hit.getSourceAsMap());
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField documents = highlightFields.get("username");
                Map<String, Object> sourceAsMap = hit.getSourceAsMap(); //这是原来的结果
                // 解析高亮的字段 将原来字段换为我们的高亮字段即可
                if(documents != null){ //即存在高亮
                    Text[] fragments = documents.fragments();
                    String new_documents = "";
                    for (Text text : fragments) {
                        new_documents += text;
                    }
                    // 将原来的替换成高亮
                    sourceAsMap.put("username",new_documents);
                }
                list.add(sourceAsMap);
            }
            long count = list.size();
            return new ResponstData(ResponseCode.SUCCESS,list,count);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponstData(ResponseCode.FAIL);
        }
    }

    /**
     * 根据id查询用户
     * */
    public ResponstData getById(Long id) {
        try {
            User user = userMapper.findById(id);
            if(user == null){
                return new ResponstData(ResponseCode.ERROR_03);
            }
            return new ResponstData(ResponseCode.SUCCESS,user);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponstData(ResponseCode.FAIL);
        }
    }

    /**
     * 根据id删除用户
     * */
    public ResponstData deleteById(Long id) {
        try {
            userMapper.deleteById(id);
            return new ResponstData(ResponseCode.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponstData(ResponseCode.FAIL);
        }
    }

    /**
     * 注册用户--用户名和密码必须
     * */
    public ResponstData insert(User user) {
        try {
            if(StringUtils.isNullOrEmpty(user.getUserName()) || StringUtils.isNullOrEmpty(user.getPassword())){
                return new ResponstData(ResponseCode.ERROR_18);
            }
            userMapper.insert(user);
            return new ResponstData(ResponseCode.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponstData(ResponseCode.FAIL);
        }
    }
}
